<template>
  <div class="image-loader-container">
    <img v-if="!everything" class="placeholder" :src="placeholder" alt="" />
    <img class="original" :src="src" alt="" @load="imgload" :style="style" />
  </div>
</template>

<script>
export default {
  props: {
    src: {
      // 原始图片路径
      type: String,
      required: true,
    },
    placeholder: {
      // 原始图片加载完成前的占位图片
      type: String,
      required: true,
    },
    duration: {
      // 原始图片加载完，切换到原始图片经过的毫秒数
      type: Number,
      default: 500,
    },
  },
  data: () => ({
    oload: false, // 原图加载完成
    everything: false, // 是否一切都完成了
  }),
  computed: {
    style() {
      return {
        transition: `opacity ${this.duration / 1000}s`,
        opacity: this.oload ? 1 : 0,
      };
    },
  },
  methods: {
    imgload() {
      this.oload = true;
      setTimeout(() => {
        this.everything = true;
        this.$emit("load");
      }, this.duration);
    },
  },
};
</script>

<style lang='less' scoped>
@import "~@/assets/style/mixin.less";
.image-loader-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  img {
    object-fit: cover;
    .pos-fill();
    &.original {
      opacity: 0;
    }
    &.loadend {
      opacity: 1;
    }
    .placeholder {
      filter: blur(2vw);
    }
  }
}
</style>
